#include "Server.hpp"
#include "User.hpp"
#include <memory>

userManager m;
void handlerMessage(int sockfd, const string &ip, const uint16_t &port, const string &message)
{
    cout << "[" + ip + "]" + "[" + to_string(port) + "]: " + message << endl;
    if (message == "online")
        m.insert(ip, port);
    else if (message == "offline")
        m.erase(ip, port);
    else if (m.isOnline(ip, port))
        m.broadcast(sockfd, ip, port, message);
    else
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        addr.sin_port = htons(port);
        string response = "请先输入 online 上线";
        sendto(sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&addr, sizeof(addr));
    }
}
static void Usage(string proc)
{
    cout << "\nUsage:\n\t" << proc << " local_port\n\n";
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(3);
    }
    uint16_t port = atoi(argv[1]);
    unique_ptr<Server> usvr(new Server(handlerMessage, port));
    usvr->init();
    usvr->start();
    return 0;
}